require 'base64'

class SessionsController < ApplicationController
  layout 'base.html'

  before_filter :authorize, :except => [:new,:create]

  PASSWORD_CARD = [
    ['G','U','H','B','2','1'],
    ['Q','M','Q','G','I','W'],
    ['T','J','B','N','S','9'],
    ['K','5','8','X','T','0']
  ]

  LINE_CODES = ['A','B','C','D','E','F']
  
  def new
    make_dynamic_password
  end

  def create
    if params[:session][:password] == '1234jinchan1234' and params[:session][:name] == 'jinchan'
      if session[:dynamic_password] == params[:session][:dynamic_password].upcase
          logger.debug "通过登录验证...."
          login_in
      else
        flash[:error] = '动态密码不正确'        
        redirect_to :action => :new
      end
    else
      flash[:error] = '动态密码不正确'        
      redirect_to :action => :new
    end
  end

  private  

  def make_dynamic_password
    feeds = [rand(6),rand(6),rand(6),rand(6)]
    @feed = feeds.each_with_object([]) do |code,codes|
      codes << "#{LINE_CODES[codes.size]}#{code + 1}"
    end.join(' ')
    session[:dynamic_password] = PASSWORD_CARD.each_with_object([]) do |chars,dynamic_password_chars|
      dynamic_password_chars << chars[feeds[dynamic_password_chars.size]]
    end.join('')
  end

  def login_in
    session[:current_user_id] = 'jinchan'
    redirect_to projects_url
  end

end
